<html>
    
    <head>
        <meta charset="utf-8">
        <title>Clone</title>
        <style>
        
        </style>
        <script>
            
            Object.prototype.clone = function(deep) {
                if (typeof this === "object") {
                    var o = {};
                    if (deep == true) {
                        for (var key in this) {
                            o[key] = (this[key].clone) ?
                                this[key].clone(deep) : this[key];
                        }
                    }
                    else {
                        for (var key in this) { o[key] = this[key]; }
                    }
                    return o;
                }
                
                return this;
            };
            
            Array.prototype.clone = function(deep) {
                if (deep == true) {
                    var a = Array(this.length);
                    for (var i=0; i<this.length; ++i) {
                        a[i] = (this[i].clone) ? this[i].clone(deep) : this[i];
                    }
                    return a;
                };
                
                return Array.apply(null, this);
            };
            
            window.addEventListener("load", function(){
                testRef();
                testClone();
                testCloneDeep(false);
                testCloneDeep(true);
            }, false);
            
            var testRef = function()
            {
                console.log("testRef");
                
                var a = [1, 2, 4];
                var b = a;
                b[3] = 8;
                console.log(a);
                console.log(b);
            };
            
            var testClone = function(){
                console.log("testClone");
                
                var a = [1, 2, 4];
                var b = a.clone();
                b[3] = 8;
                console.log(a);
                console.log(b);
            };
            
            var testCloneDeep = function(deep){
                console.log("testClone : " + String(deep));
                
                var a = [
                    [1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]
                ];
                var b = a.clone(deep);
                b[0][0] = 255;
                console.log(a);
                console.log(b);
            };
            
        </script>
    </head>
    
    <body>
        
        <h1>Clone</h1>
        
    </body>

</html>
